package com.asset.dispoal.business.mediation.service.common;

import com.asset.dispoal.business.mediation.domain.db.entity.CollectionRecord;
import com.asset.dispoal.business.mediation.domain.db.mapper.CollectionRecordMapper;
import com.asset.dispoal.business.mediation.dto.SaveCollectionRecordRequest;
import com.asset.dispoal.business.mediation.service.converter.CollectionRecordConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import tech.mhuang.pacebox.core.ddd.BaseCommand;
import tech.mhuang.pacebox.core.id.BaseIdeable;
import tech.mhuang.pacebox.core.util.StringUtil;
import tech.mhuang.pacebox.springboot.core.local.GlobalHeaderThreadLocal;
import tech.mhuang.pacebox.springboot.protocol.Result;

import java.util.Date;

/**
 * @description:
 * @author: yf
 * @date: 2022-09-13 11:11:11
 */
@Repository
public class SaveColletionCommand implements BaseCommand<SaveCollectionRecordRequest, Result> {
    @Autowired
    private BaseIdeable<String> snowflake;
    @Autowired
    private CollectionRecordMapper recordMapper;

    @Override
    public Result execute(SaveCollectionRecordRequest request) {
        CollectionRecord record = CollectionRecordConverter.INSTANCE.reqToDo(request);
        String userId = GlobalHeaderThreadLocal.getOrException().getUserId();
        if (StringUtil.isBlank(record.getId())) {
            //新增
            record.setId(snowflake.generateId());
            record.setCreateUser(userId);
            record.setCreateTime(new Date());
        }
        record.setUpdateUser(userId);
        record.setUpdateTime(new Date());
        record.setDeleted(0);
        int i = recordMapper.insertOrUpdate(record);
        return i <= 0 ? Result.faild("数据保存失败") : Result.ok();
    }
}
